//
// Created by gogoqiu on 2021/12/13.
//

#include "ChatWnd.h"
//
// This file is part of the aMule Project.
//
// Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
// Copyright (c) 2002-2011 Merkur ( devs@emule-project.net / http://www.emule-project.net )
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
//

//#include <common/MenuIDs.h>  // IDs for the chat-popup menu

//#include <wx/app.h>
//#include "wx/wx.h"

#include "ChatWnd.h"		// Interface declarations
/*
#include "amule.h"		// Needed for theApp
#include "amuleDlg.h"		// Needed for CamuleDlg
#include "ClientList.h"		// Needed for CClientList
#include "ClientRef.h"		// Needed for CClientRef
#include "FriendListCtrl.h"	// Needed for CFriendListCtrl
#include "FriendList.h"		// Needed for CFriendList
#include "Friend.h"			// Needed for CFriend
#include "ChatSelector.h"	// Needed for CChatSelector
#include "muuli_wdr.h"		// Needed for messagePage
#include "OtherFunctions.h"
*/
enum {
    MP_CLOSE_TAB,
    MP_CLOSE_ALL_TABS,
    MP_CLOSE_OTHER_TABS,
    MP_ADDFRIEND,
    IDC_CMESSAGE,
    IDC_CSEND,
    IDC_CCLOSE,
    IDC_CHATSELECTOR
};
/**
 * wxFrame
 */
BEGIN_EVENT_TABLE(CChatWnd, wxPanel )
                EVT_RIGHT_DOWN(CChatWnd::OnNMR_clickChatTab)

                EVT_MENU(MP_CLOSE_TAB,			CChatWnd::OnPopupClose)
                EVT_MENU(MP_CLOSE_ALL_TABS,		CChatWnd::OnPopupCloseAll)
                EVT_MENU(MP_CLOSE_OTHER_TABS,	CChatWnd::OnPopupCloseOthers)
                EVT_MENU(MP_ADDFRIEND,			CChatWnd::OnAddFriend )
                //
                EVT_TEXT_ENTER(IDC_CMESSAGE, CChatWnd::OnBnClickedCsend)
                EVT_BUTTON(IDC_CSEND, CChatWnd::OnBnClickedCsend)
                EVT_BUTTON(IDC_CCLOSE, CChatWnd::OnBnClickedCclose)
                //EVT_MULENOTEBOOK_ALL_PAGES_CLOSED(IDC_CHATSELECTOR, CChatWnd::OnAllPagesClosed)
END_EVENT_TABLE()


CChatWnd::CChatWnd(wxWindow* pParent)
        : wxPanel(pParent, -1)
{
    /*
    wxSizer* content = messagePage(this, true);
    content->Show(this, true);

    chatSelector = CastChild(IDC_CHATSELECTOR, CChatSelector );
    // We want to use our own popup menu
    chatSelector->SetPopupHandler(this);
    m_menu = nullptr;

    friendListCtrl = CastChild(ID_FRIENDLIST, CFriendListCtrl );*/
}

void CChatWnd::StartSession(CFriend* friend_client, bool setFocus)
{
    /*
    if ( !friend_client->GetName().IsEmpty() ) {
        if (setFocus) {
            theApp->amuleDlg->SetActiveDialog(CamuleDlg::DT_CHAT_WND, this);
        }
        chatSelector->StartSession(GUI_ID(friend_client->GetIP(),
                                          friend_client->GetPort()), friend_client->GetName(), true);
    }

    // Check to enable the window controls if needed
    CheckNewButtonsState();*/
}


void CChatWnd::OnNMR_clickChatTab(wxMouseEvent& evt)
{
    /*
    // Only handle events from the chat-notebook
    if (evt.GetEventObject() != (wxObject*)chatSelector)
        return;

    if (chatSelector->GetSelection() == -1) {
        return;
    }

    // Avoid opening another menu when it's already open
    if (m_menu == nullptr) {
        m_menu = new wxMenu(_("Chat"));

        m_menu->Append(MP_CLOSE_TAB, wxString(_("Close tab")));
        m_menu->Append(MP_CLOSE_ALL_TABS, wxString(_("Close all tabs")));
        m_menu->Append(MP_CLOSE_OTHER_TABS, wxString(_("Close other tabs")));

        m_menu->AppendSeparator();

        wxMenuItem * addFriend = m_menu->Append(MP_ADDFRIEND, _("Add to Friends"));

        // Disable this client if it is already a friend
        CClientRef client;
        if (chatSelector->GetCurrentClient(client) && client.IsFriend()) {
            addFriend->Enable(false);
        }

        PopupMenu(m_menu, evt.GetPosition());

        delete m_menu;
        m_menu = nullptr;
    }*/
}


void CChatWnd::OnPopupClose(wxCommandEvent& WXUNUSED(evt))
{
    //chatSelector->DeletePage(chatSelector->GetSelection());
}


void CChatWnd::OnPopupCloseAll(wxCommandEvent& WXUNUSED(evt))
{
    //chatSelector->DeleteAllPages();
}


void CChatWnd::OnPopupCloseOthers(wxCommandEvent& WXUNUSED(evt))
{
    /*
    wxNotebookPage* current = chatSelector->GetPage(chatSelector->GetSelection());

    for (int i = chatSelector->GetPageCount() - 1; i >= 0; i--) {
        if (current != chatSelector->GetPage(i))
            chatSelector->DeletePage(i );
    }*/
}

//线程不断侦听一个口子，如同socket, listen it
//wait
//epoll
//注入管道
//message
//static
//wndproc, c, c++( this )
//post the message, pack the this point to the message, on get the message, to separate the this point
//send the message to self, how to send the message to self
//queue
//thread read
//udp
//JMUDPConnection
//open
/*
 * udpListenThread = new UDPListenThread();
			udpListenThread.start();

			sender_thread = new UDPSenderThread();
			sender_thread.start();
    PacketReader.readUDPPacket ( listenChannel );

    UDPPacket packet = sendQueue.poll();
    listenChannel.send ( packet.getAsByteBuffer(), destination );
    write( socket )
    recv( socket )
    核心资源
    channel
    select
    wait to be interrupt, thread wait to be interrupt
    锁
    notify
    use "select" seek all the keyboard/mouse and others file id, wait the socket the change
    内核派发消息。如同一个服务器程序。keyboard侦听，其实就是侦听一个file id。激活相应thread
    window状态，派发到相应消息队列，激活线程
    getMessage()=>加入到等待中去，等待被唤醒
    一定的公共结构，内核程序可以访问
 */
void CChatWnd::OnAddFriend(wxCommandEvent& WXUNUSED(evt))
{
    /*
    // Get the client that the session is open to
    CClientRef client;

    // Add the client as friend unless it's already a friend
    if (chatSelector->GetCurrentClient(client) && !client.IsFriend()) {
        theApp->friendList->AddFriend(client);
    }
     */
}


void CChatWnd::OnBnClickedCsend(wxCommandEvent& WXUNUSED(evt))
{
    /*
    wxString message = CastChild(IDC_CMESSAGE, wxTextCtrl)->GetValue();

    SendMessage(message);*/
}


void CChatWnd::OnBnClickedCclose(wxCommandEvent& WXUNUSED(evt))
{
    //chatSelector->EndSession();
}


void CChatWnd::OnAllPagesClosed(wxNotebookEvent& WXUNUSED(evt))
{
    //CastChild(IDC_CMESSAGE, wxTextCtrl)->Clear();
    // Check to disable the window controls
    CheckNewButtonsState();
}


void CChatWnd::UpdateFriend(CFriend* toUpdate)
{
    /*
    if (toUpdate->GetLinkedClient().IsLinked()) {
        chatSelector->RefreshFriend(GUI_ID(toUpdate->GetIP(),
                                           toUpdate->GetPort()), toUpdate->GetName());
    } else {
        // drop Chat session
        chatSelector->EndSession(GUI_ID(toUpdate->GetIP(), toUpdate->GetPort()));
    }
    friendListCtrl->UpdateFriend(toUpdate);
     */
}


void CChatWnd::RemoveFriend(CFriend* toDel)
{
    /*
    chatSelector->EndSession(GUI_ID(toDel->GetIP(), toDel->GetPort()));
    friendListCtrl->RemoveFriend(toDel);*/
}


void CChatWnd::ProcessMessage(uint64 sender, const wxString& message)
{
    /*
    if ( !theApp->amuleDlg->IsDialogVisible(CamuleDlg::DT_CHAT_WND) ) {
        theApp->amuleDlg->SetMessageBlink(true);
    }
    if (chatSelector->ProcessMessage(sender, message)) {
        // Check to enable the window controls if needed
        CheckNewButtonsState();
    }*/
}


void CChatWnd::ConnectionResult(bool success, const wxString& message, uint64 id)
{
    //chatSelector->ConnectionResult(success, message, id);
}


void CChatWnd::SendMessage(const wxString& message, const wxString& client_name, uint64 to_id)
{
/*
    if (chatSelector->SendMessage(message, client_name, to_id )) {
        CastChild(IDC_CMESSAGE, wxTextCtrl)->Clear();
    }

    // Check to enable the window controls if needed
    CheckNewButtonsState();
    CastChild(IDC_CMESSAGE, wxTextCtrl)->SetFocus();*/
}


void CChatWnd::CheckNewButtonsState()
{
    /*
    switch (chatSelector->GetPageCount()) {
        case 0:
            GetParent()->FindWindow(IDC_CSEND)->Enable(false);
            GetParent()->FindWindow(IDC_CCLOSE)->Enable(false);
            GetParent()->FindWindow(IDC_CMESSAGE)->Enable(false);
            break;
        case 1:
            GetParent()->FindWindow(IDC_CSEND)->Enable(true);
            GetParent()->FindWindow(IDC_CCLOSE)->Enable(true);
            GetParent()->FindWindow(IDC_CMESSAGE)->Enable(true);
            break;
        default:
            // Nothing to be done here. Keep current state, which should be enabled.
            wxASSERT(GetParent()->FindWindow(IDC_CSEND)->IsEnabled());
            wxASSERT(GetParent()->FindWindow(IDC_CCLOSE)->IsEnabled());
            wxASSERT(GetParent()->FindWindow(IDC_CMESSAGE)->IsEnabled());
            break;
    }*/
}


bool CChatWnd::IsIdValid(uint64 id)
{
    //return chatSelector->GetTabByClientID(id) >= 0;
    return true;
}


void CChatWnd::ShowCaptchaResult(uint64 id, bool ok)
{
    //chatSelector->ShowCaptchaResult(id, ok);
}

void CChatWnd::EndSession(uint64 id)
{
    //chatSelector->EndSession(id);
}

// File_checked_for_headers
